package cn.org.july.weixin.service.event;

import cn.org.july.weixin.common.constant.EventType;
import cn.org.july.weixin.common.constant.WxConstant;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @auther: wanghongjie
 * @blame: wanghongjie
 * @date: 2020-09-03 07:01
 * @Description:
 */
public class MessageSource implements EventSource {
    private List<EventListener> listeners = new ArrayList<>();

    private Map<String, Object> map;
    private String message;

    @Override
    public void addListener(EventListener listener) {
        listeners.add(listener);
    }

    @Override
    public void notifyListener() {
        for (EventListener listener : listeners) {
            String eventType = map.get(WxConstant.EVENT).toString();
            if (EventType.eventType(eventType) == listener.getEvent()) {
                MessageEvent event = new MessageEvent();
                event.setMap(map);
                event.setSource(this);
                message = listener.handleEvent(event);
            }
        }
    }

    public String setMap(Map<String, Object> map) {
        this.map = map;
        notifyListener();
        return message;
    }
}
